'use strict';

const BaseController = require("./base");

class PassController extends BaseController {

    /**
     * 绑定手机号码
     */
    async bindPhone() {
        /**
         * 业务走小程序，同一主体，根据Uid判断
         * 1，验证，短信码，验证码，手机号
         * 2，判断手机验证码是否过期
         */
        let { uId, phoneId, phone_code, identify_code, sign } = this.ctx.request.body;
        let add_day = await this.service.tools.getDay();         //年月日   

        if (identify_code !== this.ctx.session.identify_code) {
            //重新生成验证码 为了安全
            await this.verify();
            this.faile("输入的图形验证码不正确", -5011);
            return;
        }

        if (phone_code !== this.ctx.session.phone_code) {
            this.faile("手机验证码不正确", -5012);
            return;
        }

        let userTempResult = await this.ctx.service.userTemp.queryTemp({ sign, phoneId, add_day });
        if (userTempResult.length <= 0) {
            await this.verify();
            return this.faile("未查询到用户数据", -5009);
        }

        let nowTime = await this.service.tools.getTime();//判断验证码是否超时
        if ((userTempResult[0].add_time - nowTime) / 1000 / 60 > 30) {
            await this.verify();
            return this.faile("验证码已经过期", -5010);
        }

        let { idType } = this.ctx.helper;
        let res = await this.ctx.service.user.updateOneUser(idType.wxId, uId, { phoneId });
        if (res.ok === 1 && res.n === 1) {
            this.success("绑定成功");
        } else {//绑定失败，重新生成验证码
            await this.verify();
            this.faile(`绑定失败---${JSON.stringify(res)}`, -5013);
        }

    }

    //验证码
    async verify() {
        let captcha = await this.service.tools.captcha(120, 50);  //服务里面的方法
        this.ctx.session.identify_code = captcha.text;   /*验证码的信息*/
        this.ctx.response.type = 'image/svg+xml';   /*指定返回的类型*/
        this.ctx.body = captcha.data;      /*给页面返回一张图片*/
    }

    //发送短信验证码
    async sendCode() {
        let phoneId = this.ctx.request.query.phoneId;
        let identify_code = this.ctx.request.query.identify_code;  //用户输入的验证码
        if (identify_code !== this.ctx.session.identify_code) {
            this.faile("输入的图形验证码不正确", -5006);
        } else {
            //判断手机格式是否合法
            let reg = /^[\d]{11}$/;
            if (!reg.test(phoneId)) {
                this.faile("手机号不合法", -5002);
            } else {
                let add_day = await this.service.tools.getDay();         //年月日    
                let add_time = await this.service.tools.getTime();        //增加时间
                let sign = await this.service.tools.md5(phoneId + add_day);  //签名
                let ip = this.ctx.request.ip.replace(/::ffff:/, '');     //获取客户端ip         
                let phone_code = await this.service.tools.getRandomNum();  //发送短信的随机码    

                let userTempResult = await this.ctx.service.userTemp.queryTemp({ sign, add_day });

                if (userTempResult.length > 0) {
                    //1个ip 一天只能发10个手机号
                    let queryIp = await this.ctx.service.userTemp.queryTemp({ ip, add_day });
                    let ipCount = queryIp.length;
                    if (userTempResult[0].send_count < 6 && ipCount < 10) {                     //执行发送
                        let send_count = userTempResult[0].send_count + 1;
                        await this.ctx.service.userTemp.updateOneTemp({ "_id": userTempResult[0]._id }, { "send_count": send_count, 'add_time': add_time });
                        //发送短信
                        this.ctx.session.phone_code = phone_code;
                        console.log("验证码---", phone_code, "   签名---", sign);
                        this.success({ sign });
                    } else {
                        this.faile("当前手机号码发送次数达到上限，明天重试", -5008);
                    }

                } else {
                    await this.ctx.service.userTemp.addTemp({ phoneId, add_day, sign, ip, send_count: 1 });
                    this.ctx.session.phone_code = phone_code;
                    console.log("验证码---", phone_code, "   签名---", sign);
                    this.success({ sign });
                }
            }
        }
    }

    //验证验证码(注册，登录用)
    async validatePhoneCode() {
        let sign = this.ctx.request.query.sign;
        let phone_code = this.ctx.request.query.phone_code;
        let add_day = await this.service.tools.getDay();         //年月日   
        if (this.ctx.session.phone_code !== phone_code) {
            this.faile("您输入的手机验证码错误", -5008);
        } else {
            let userTempResult = await this.ctx.service.userTemp.queryTemp({ sign, add_day });
            if (userTempResult.length <= 0) {
                this.faile("参数错误", -5009);
            } else {
                let nowTime = await this.service.tools.getTime();//判断验证码是否超时
                if ((userTempResult[0].add_time - nowTime) / 1000 / 60 > 30) {
                    this.faile("验证码已经过期", -5010);
                } else { //用户表有没有当前这个手机号  手机号有没有注册
                    let phoneId = userTempResult[0].phoneId;
                    let userResult = await this.ctx.service.userTemp.queryTemp({ phoneId });
                    if (userResult.length > 0) {
                        this.faile("此用户已经存在", -5011);
                    } else {
                        this.success({ sign });
                    }
                }
            }
        }
    }
}
module.exports = PassController;
